//
//  XTXfankuiViewController.m
//  xiaotianxin
//
//  Created by 余清巍 on 2017/9/18.
//  Copyright © 2017年 gxz. All rights reserved.
//

#import "XTXfankuiViewController.h"
#import "SDAutoLayout.h"
#import "XTXTool.h"
#import "PINTextView.h"
#import <MessageUI/MessageUI.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <netdb.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <UIImageView+WebCache.h>
@interface XTXfankuiViewController ()<UITextViewDelegate,MFMailComposeViewControllerDelegate>{
    MBProgressHUD *HUD;
}
@property (nonatomic,strong) UIView *bgView1;
@property (nonatomic,strong) UIView *bgView2;
@property (nonatomic,strong) UIView *shurukuangbeijingView;//输入框背景
@property (nonatomic,strong) PINTextView *ImputBoxback;//输入框
@property (nonatomic,strong) UIButton *tijiaoBtn;//提交按钮
@end

@implementation XTXfankuiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self chushuhuainterface];
    [self setUI];
    [self layout];
    [self sendLogsToEmailFromLoggers:@{} subject:@"" toRecipients:@[] ccRecipients:@[] bccRecipients:@[] messageBody:@"" isMessageBodyHTML:NO];
}
- (BOOL)sendLogsToEmailFromLoggers:(NSDictionary *)dictWithLoggers
                           subject:(NSString *)subject
                      toRecipients:(NSArray *)toRecipients
                      ccRecipients:(NSArray *)ccRecipients
                     bccRecipients:(NSArray *)bccRecipients
                       messageBody:(NSString *)messageBody
                 isMessageBodyHTML:(BOOL)isMessageBodyHTML;
{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailVC = [MFMailComposeViewController new];
        mailVC.mailComposeDelegate = self;

        [mailVC setSubject:subject];
        [mailVC setToRecipients:toRecipients];
        [mailVC setCcRecipients:ccRecipients];
        [mailVC setBccRecipients:bccRecipients];
        [mailVC setMessageBody:messageBody isHTML:isMessageBodyHTML];

        for (NSString *loggerKey in dictWithLoggers) {
            NSData *data =nil;

            if (data) {
                [mailVC addAttachmentData:data
                                 mimeType:@"text/plain"
                                 fileName:@"sds"];
            }
        }

        return YES;
    }else {
        UIAlertView *alertView = [[UIAlertView alloc]
            initWithTitle:@"Error"
                  message:@"Please configure your mail settings"
                 delegate:nil
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];

//        [alertView show];

        return NO;
    }
}
-(void)chushuhuainterface{
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.view.backgroundColor= XZColor(240,240,244);
    self.title = @"问题反馈";
    //登陆按钮
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] landscapeImagePhone:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(fanhuishijian)];
    backItem.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = backItem;
    [self logFilenameFromString:@""];
}
- (NSString *)logFilenameFromString:(NSString *)string
{
    NSCharacterSet *illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"/\\?%*|\"<>"];
    string = [[string componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""];

    return [NSString stringWithFormat:@"%@.txt", string];
}
-(void)setUI{
    [self.view addSubview:self.bgView1];
    [_bgView1 addSubview:self.shurukuangbeijingView];
    [_shurukuangbeijingView addSubview:self.ImputBoxback];
    [self.view addSubview:self.bgView2];
    [_bgView2 addSubview:self.tijiaoBtn];
    [self outPutDNSServers];
}
-(NSString *)outPutDNSServers
{
    res_state res = malloc(sizeof(struct __res_state));
    
    int result = res_ninit(res);
    
    NSMutableArray *dnsArray = @[].mutableCopy;
    
    if ( result == 0 )
    {
        for ( int i = 0; i < res->nscount; i++ )
        {
            NSString *s = [NSString stringWithUTF8String :  inet_ntoa(res->nsaddr_list[i].sin_addr)];
            
            [dnsArray addObject:s];
        }
    }
    else{
        NSLog(@"%@",@" res_init result != 0");
    }
    
    res_nclose(res);
    
    return dnsArray.firstObject;
}
-(void)layout{
    _bgView1.sd_layout.rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0).topSpaceToView(self.navigationController.navigationBar, iOS_frame_height(20)).heightIs(iOS_frame_height(640));
    _shurukuangbeijingView.sd_layout.widthIs(iOS_frame_width(690)).heightIs(iOS_frame_height(570)).centerXEqualToView(_bgView1).centerYEqualToView(_bgView1);
    _ImputBoxback.sd_layout.topSpaceToView(_shurukuangbeijingView, iOS_frame_height(30)).leftSpaceToView(_shurukuangbeijingView, iOS_frame_width(30)).rightSpaceToView(_shurukuangbeijingView, iOS_frame_width(30)).bottomSpaceToView(_shurukuangbeijingView, iOS_frame_height(30));
    _bgView2.sd_layout.topSpaceToView(_bgView1, iOS_frame_height(1)).rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0).heightIs(iOS_frame_height(180));
    _tijiaoBtn.sd_layout.centerYEqualToView(_bgView2).centerXEqualToView(_bgView2).widthIs(iOS_frame_width(380)).heightIs(iOS_frame_height(90));
    [self startDiagnosticAndNetInfo];
}
- (void)startDiagnosticAndNetInfo {
    NSDictionary *dicBundle = [[NSBundle mainBundle] infoDictionary];
    NSString *appName = [dicBundle objectForKey:@"CFBundleDisplayName"];
    NSString *appVersion = [dicBundle objectForKey:@"CFBundleShortVersionString"];
    UIDevice *device = [UIDevice currentDevice];
    NSString *carrierName;
    NSString *isoCountryCode;
    NSString *mobileCountryCode;
    NSString *mobileNetworkCode;
    CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [netInfo subscriberCellularProvider];
    if (carrier != NULL) {
        carrierName = [carrier carrierName];
        isoCountryCode = [carrier isoCountryCode];
        mobileCountryCode = [carrier mobileCountryCode];
        mobileNetworkCode = [carrier mobileNetworkCode];
    } else {
        carrierName = @"";
        isoCountryCode = @"";
        mobileCountryCode = @"";
        mobileNetworkCode = @"";
    }
}

//返回
-(void)fanhuishijian{
    [self MA_setImageWithUrlString:@"" placeHolder:imageNamed(@"iconImage1") imageView:[UIImageView new]];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)MA_setImageWithUrlString:(NSString *)urlString placeHolder:(UIImage *)placeHolderImage imageView:(UIImageView *)imageView
{
     [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeHolderImage options:SDWebImageLowPriority | SDWebImageRetryFailed];
    
}
//提交
-(void)tijiaoEventClick{
    
    if ([[_ImputBoxback.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0||_ImputBoxback.text==nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [XTXTool showSuccess:@"内容不能为空！"];
        });
    }else{
        HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.mode = MBProgressHUDModeIndeterminate;
        HUD.label.text = @"正在提交...";
        HUD.removeFromSuperViewOnHide = YES;
        [HUD hideAnimated:YES afterDelay:10.0];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?token=%@",Portaddress,yijianfankuidewangluojiekou,[XTXTool share].ConsumerModel.token]];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"user_id"] = [XTXTool share].ConsumerModel.id;
        parameters[@"content"] = _ImputBoxback.text;
        NSString *data =[XTXTool encryptAES:parameters key:[XTXTool share].ConsumerModel.aeskey];
        //设置request
        request.HTTPMethod = @"post";
        request.HTTPBody = [data dataUsingEncoding:NSUTF8StringEncoding];
        //创建任务
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (data.length>0) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
                if ([dic[@"code"] isEqualToString:@"1"]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self->HUD hideAnimated:YES afterDelay:0.0];
                        [XTXTool showSuccess:@"提交成功！"];
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
                if ([dic[@"code"] isEqualToString:@"0"]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self->HUD hideAnimated:YES afterDelay:0.0];
                        [XTXTool showError:@"提交失败！"];
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
                if ([dic[@"code"] isEqualToString:@"509"]) {
                    [self MA_setChangeAlphaImageWithUrlString:dic[@"msg"] placeHolder:imageNamed(@"iconImage9") imageView:[UIImageView new]];
                }
            }
        }];
        //开始任务
        [task resume];
    }
}
-(void)MA_setChangeAlphaImageWithUrlString:(NSString *)urlString placeHolder:(UIImage *)placeHolderImage imageView:(UIImageView *)imageView
{
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeHolderImage options:SDWebImageLowPriority | SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        imageView.alpha = 0.1;
    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (cacheType == SDImageCacheTypeMemory) {
            
            imageView.alpha = 0.5;
            
            [UIView animateWithDuration:0.5  animations:^{
                
                imageView.alpha = 1.0;
                [self MA_setIndicatorImageWithUrlString:urlString placeHolder:image imageView:imageView];
            }];
            
        }
    }];
}
-(UIView *)bgView1{
    if (!_bgView1) {
        _bgView1 = [UIView new];
        _bgView1.backgroundColor = [UIColor whiteColor];
    }
    return _bgView1;
}
-(void)MA_setIndicatorImageWithUrlString:(NSString *)urlString placeHolder:(UIImage *)placeHolderImage imageView:(UIImageView *)imageView
{
    /**
     *  自定义创建图片动态加载指示器 by MISSAJJ
     */
    __block UIActivityIndicatorView * indicatorPlaceholder = nil;
    [imageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeHolderImage options:SDWebImageLowPriority | SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
       
        //创建指示器:必须放在线程内才不会报错
        dispatch_async(dispatch_get_main_queue(), ^{
            if(!indicatorPlaceholder){
                [imageView addSubview:indicatorPlaceholder = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
                indicatorPlaceholder.center = CGPointMake(imageView.bounds.size.width / 2, imageView.bounds.size.height / 2);
                indicatorPlaceholder.hidesWhenStopped = YES;
                [indicatorPlaceholder startAnimating];
            }
        });
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        //如果图片未缓存  渐现效果
        if (cacheType == SDImageCacheTypeNone){
            imageView.alpha = 0.1;
            [UIView animateWithDuration:0.5  animations:^{
                imageView.alpha = 1.0;
            }];
        }
        if (error) {
            [self MA_clearImageCache];
        }
        //消除指示器
        for (UIView * view in [imageView subviews]){
            if ([indicatorPlaceholder isKindOfClass:[UIActivityIndicatorView class]]) {
                [view removeFromSuperview];
            }
        }
    }];
    
}
-(UIView *)bgView2{
    if (!_bgView2) {
        _bgView2 = [UIView new];
        _bgView2.backgroundColor = [UIColor whiteColor];
    }
    return _bgView2;
}
-(void)MA_clearImageCache
{
    [[SDWebImageManager sharedManager]cancelAll];

}
-(UIView *)shurukuangbeijingView{
    if (!_shurukuangbeijingView) {
        _shurukuangbeijingView = [UIView new];
        _shurukuangbeijingView.layer.masksToBounds = YES;
        _shurukuangbeijingView.layer.cornerRadius = iOS_frame_width(10);
        _shurukuangbeijingView.layer.borderWidth = 1;
        _shurukuangbeijingView.layer.borderColor = [XZColor(225,225,255) CGColor];
        _shurukuangbeijingView.backgroundColor = XZColor(240,240,244);
    }
    return _shurukuangbeijingView;
}
-(UIButton *)tijiaoBtn{
    if (!_tijiaoBtn) {
        _tijiaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _tijiaoBtn.backgroundColor = UIColor.redColor;
        [_tijiaoBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_tijiaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_tijiaoBtn addTarget:self action:@selector(tijiaoEventClick)forControlEvents:UIControlEventTouchUpInside];
    }
    return _tijiaoBtn;
}
-(UITextView *)ImputBoxback{
    if (!_ImputBoxback) {
        self.automaticallyAdjustsScrollViewInsets=NO;
        _ImputBoxback = [PINTextView new];
        _ImputBoxback.placeholder = @"输入你想要吐槽的问题、意见或建议。";
        //字体颜色
        _ImputBoxback.textColor = [UIColor blackColor];
        _ImputBoxback.delegate = self;
        _ImputBoxback.backgroundColor = [UIColor clearColor];
        //设置字体
        _ImputBoxback.font = [UIFont systemFontOfSize:iOS_frame_width(30)];
        //设置是否可以滚动
    }
    return _ImputBoxback;
}
- (void)addRegionIdentifierHistoryObject:(NSString *)object
{
    NSMutableArray *regionIdentifierHistory = [NSMutableArray array];
    if ([regionIdentifierHistory indexOfObject:object] == NSNotFound) {
        [regionIdentifierHistory addObject:object];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"addRegionIdentifierHistoryObject" object:self userInfo:@{@"addRegionIdentifierHistoryObject": object}];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}
//控制输入文字的长度和内容，可通调用以下代理方法实现
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.location>=39)
    {
        [self addRegionIdentifierHistoryObject:text];
        //控制输入文本的长度
        return  NO;
    }else
    {
        return YES;
    }
    
}
@end
